#{extends 'main.html' /}
#{set title:'Home' /}

#{if flash.success}
<p class="success">${flash.success}</p>
#{/if}

#{if game}
<script type="text/javascript">
    $(document).ready(function() {
        var canvas = $("#canvas");

        var size = ${game.board.size};
        var stat = ${game.myStatusCode};
        var gameId = ${game.id};
        var playerId = "${playerId}";
        var player = '${player}'
        var lastReceived = ${lastReceived};

        var game = new Game( canvas, size );

        // update game state
        game.playerTurn = '${game.playerTurn}';
        game.playerBlackPoints = ${game.playerBlackPoints};
        game.playerWhitePoints = ${game.playerWhitePoints};
        game.board.setPositionsFromString("${game.board.positions}")

        game.draw();
        updateScoreBoard();
    
        var waitMessages = #{jsAction @waitMessages(':lastReceived', ':playerId') /}
    
        // Retrieve long-polling messages
        var getMessages = function() {
            $.ajax({
                url: waitMessages({lastReceived: lastReceived, playerId: playerId}),
                success: function(events) {
                    $(events).each(function() {
                        handleMessage(this.data)
                        lastReceived = this.id
                    })
                    getMessages()
                },
                dataType: 'json'
            });
        }
        getMessages();
    
        // Handle long-polling messages
        var handleMessage = function(msg) {
            if (msg.type == "playermove"){
                $('#debugger2').append(msg.type+"("+msg.x+","+msg.y+")");
                if ( game.playerTurn == player ){
                    alert("Error. Received move from opponent during your turn");
                    return;
                }
                if (game.play(msg.x, msg.y)) {
                    updateScoreBoard();
                } else {
                    alert("Error. Received illegal move from opponent!");
                }                 
            }
        }



       canvas.mouseup(function(e) {
            var pos = getCursorPosition(e);
            var boardPos = game.boardCanvas.screenPosToBoardPos(pos);
            play(boardPos[0], boardPos[1]);
        });


        function getCursorPosition(event) {
            var x, y;
            canoffset = canvas.offset();
            x = event.clientX + document.body.scrollLeft + document.documentElement.scrollLeft - Math.floor(canoffset.left);
            y = event.clientY + document.body.scrollTop + document.documentElement.scrollTop - Math.floor(canoffset.top) + 1;
            return [x,y];
        }

        function play(x,y) {
            if ( game.playerTurn != player ){
                alert("Not your turn!");
                return false;
            }

            if (game.play(x,y)) {
                updateScoreBoard();
                submitMove(x,y);
                return true;
            }
            else {
                alert("illegal move!");
                return false;
            }       
        }

        function submitMove(x, y) {
            var gamedata = {
                "playerId" : playerId,
                "x" : x,
                "y" : y
            };
            $.ajax({
                type: "POST",
                url: "play/" + gameId,
                data: gamedata,
                beforeSend: function() {
                    $('#ajax').text("Sending....");
                },
                error: function() {
                    $("#ajax").text("Error when sending to server!");
                },
                success: function(data) {
                    $("#ajax").text("Success!");
                    var retVal = data.myStatusCode;
                    $("#ajax").append(retVal);
                    // TODO: check that server state is the same as client state
                    // myGame = game(canvas, size, data.playerTurn);
                    // myGame.setPositionsFromString(data.board.positions);
                    // playerBlackPoints = data.playerBlackPoints;
                    // playerWhitePoints = data.playerWhitePoints;
                    // playerTurn = data.playerTurn;
                    // myGame.draw();
                    // updateScoreBoard();
                },
                complete: function(data) {
                    $("#ajax").append("...Ferdig!");

                }
            });
        }

        function updateScoreBoard() {
            if (game.playerTurn == 'B') {
                currentPlayer = "Black's";
            } else {
                currentPlayer = "White's";
            }
            $("#blackPoints").text(game.playerBlackPoints);
            $("#whitePoints").text(game.playerWhitePoints);
            $("#playerTurn").text(currentPlayer);
            $("#error").text("");
        }
    });

</script>
<div class="game">
    <div id="scoreboard">
    <table border="1" bordercolor="#FFCC00" style="background-color:#FFFFCC" width="550" cellpadding="3" cellspacing="3">
        <tr>
    		<td><div id="black">
                Black : <span id="blackPoints"> 0 </span> points
            </div></td>
    		<td><div id="turn">
                <span id="playerTurn">Black's</span> turn
            </div></td>
    		<td><div id="white">
                White : <span id="whitePoints"> 0 </span> points
            </div></td>
    	</tr>
    </table>
    </div>
    <div id="error">
        #{if flash.error}
        <p class="error">${flash.error}</p>
        #{/if}
    </div>
    <div id="board">
        <canvas width="550" height="550" id="canvas"/>
    </div>

    
    <div id="ajax">

    </div>
    <div id="debugger">
        ${game.myStatusCode}

    </div>
    <div id="debugger2">

    </div>
</div>
link for black player: <a href="@{Application.show(game.id, game.playerBlackId )}">Black</a>
link for white player: <a href="@{Application.show(game.id, game.playerWhiteId )}">White</a>
#{/if}

